<template>
  <div class="space-manage-container">
    <a-card title="空间管理" :bordered="false">
      <!-- 搜索区域 -->
      <div class="search-form">
        <a-form :model="searchForm" layout="inline" @finish="handleSearch">
          <a-form-item label="空间名称" name="spaceName">
            <a-input
              v-model:value="searchForm.spaceName"
              placeholder="请输入空间名称"
              style="width: 200px"
              allow-clear
            />
          </a-form-item>
          <a-form-item label="空间级别" name="spaceLevel">
            <a-select
              v-model:value="searchForm.spaceLevel"
              placeholder="请选择空间级别"
              style="width: 120px"
              allow-clear
            >
              <a-select-option
                v-for="option in SPACE_LEVEL_OPTIONS"
                :key="option.value"
                :value="option.value"
              >
                {{ option.label }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="空间类型" name="spaceType">
            <a-select
              v-model:value="searchForm.spaceType"
              placeholder="请选择空间类型"
              style="width: 120px"
              allow-clear
            >
              <a-select-option
                v-for="option in SPACE_TYPE_OPTIONS"
                :key="option.value"
                :value="option.value"
              >
                {{ option.label }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item>
            <a-space>
              <a-button type="primary" html-type="submit" :loading="loading">
                <template #icon><SearchOutlined /></template>
                搜索
              </a-button>
              <a-button @click="handleReset">
                <template #icon><ReloadOutlined /></template>
                重置
              </a-button>
            </a-space>
          </a-form-item>
        </a-form>
      </div>

      <!-- 统计信息 -->
      <div class="stats-cards">
        <a-row :gutter="16">
          <a-col :span="6">
            <a-statistic title="总空间数" :value="stats.total" :value-style="{ color: '#1890ff' }">
              <template #prefix>
                <DatabaseOutlined />
              </template>
            </a-statistic>
          </a-col>
          <a-col :span="6">
            <a-statistic
              title="个人空间"
              :value="stats.personal"
              :value-style="{ color: '#52c41a' }"
            >
              <template #prefix>
                <UserOutlined />
              </template>
            </a-statistic>
          </a-col>
          <a-col :span="6">
            <a-statistic title="团队空间" :value="stats.team" :value-style="{ color: '#722ed1' }">
              <template #prefix>
                <TeamOutlined />
              </template>
            </a-statistic>
          </a-col>
          <a-col :span="6">
            <a-statistic
              title="今日新增"
              :value="stats.todayNew"
              :value-style="{ color: '#fa8c16' }"
            >
              <template #prefix>
                <PlusOutlined />
              </template>
            </a-statistic>
          </a-col>
        </a-row>
      </div>

      <!-- 空间列表 -->
      <div class="space-list">
        <a-table
          :columns="columns"
          :data-source="spaceList"
          :loading="loading"
          :pagination="pagination"
          @change="handleTableChange"
          row-key="id"
        >
          <template #bodyCell="{ column, record }">
            <!-- 空间名称 -->
            <template v-if="column.key === 'spaceName'">
              <div class="space-name-cell">
                <a-typography-text strong>{{ record.spaceName }}</a-typography-text>
                <div class="space-id">ID: {{ record.id }}</div>
              </div>
            </template>

            <!-- 空间级别 -->
            <template v-else-if="column.key === 'spaceLevel'">
              <a-tag :color="getSpaceLevelColor(record.spaceLevel)">
                {{ getSpaceLevelText(record.spaceLevel) }}
              </a-tag>
            </template>

            <!-- 空间类型 -->
            <template v-else-if="column.key === 'spaceType'">
              <a-tag :color="getSpaceTypeColor(record.spaceType)">
                {{ getSpaceTypeText(record.spaceType) }}
              </a-tag>
            </template>

            <!-- 创建时间 -->
            <template v-else-if="column.key === 'createTime'">
              {{ formatDate(record.createTime) }}
            </template>

            <!-- 操作 -->
            <template v-else-if="column.key === 'action'">
              <a-space>
                <a-button type="link" size="small" @click="handleView(record)">
                  <template #icon><EyeOutlined /></template>
                  查看
                </a-button>
                <a-button type="link" size="small" @click="handleEdit(record)">
                  <template #icon><EditOutlined /></template>
                  编辑
                </a-button>
                <a-popconfirm
                  title="确定要删除这个空间吗？"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="handleDelete(record)"
                >
                  <a-button type="link" size="small" danger>
                    <template #icon><DeleteOutlined /></template>
                    删除
                  </a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </template>
        </a-table>
      </div>
    </a-card>

    <!-- 空间详情弹窗 -->
    <a-modal
      v-model:open="detailModalVisible"
      title="空间详情"
      width="800px"
      :footer="null"
      centered
    >
      <div v-if="currentSpace" class="space-detail">
        <a-descriptions title="基本信息" :column="2" bordered>
          <a-descriptions-item label="空间ID">{{ currentSpace.id }}</a-descriptions-item>
          <a-descriptions-item label="空间名称">{{ currentSpace.spaceName }}</a-descriptions-item>
          <a-descriptions-item label="空间级别">
            <a-tag :color="getSpaceLevelColor(currentSpace.spaceLevel)">
              {{ getSpaceLevelText(currentSpace.spaceLevel) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="空间类型">
            <a-tag :color="getSpaceTypeColor(currentSpace.spaceType)">
              {{ getSpaceTypeText(currentSpace.spaceType) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="创建用户ID">{{ currentSpace.userId }}</a-descriptions-item>
          <a-descriptions-item label="创建时间">{{
            formatDate(currentSpace.createTime)
          }}</a-descriptions-item>
          <a-descriptions-item label="编辑时间">{{
            formatDate(currentSpace.editTime)
          }}</a-descriptions-item>
          <a-descriptions-item label="更新时间">{{
            formatDate(currentSpace.updateTime)
          }}</a-descriptions-item>
        </a-descriptions>
      </div>
    </a-modal>

    <!-- 编辑空间弹窗 -->
    <a-modal
      v-model:open="editModalVisible"
      title="编辑空间"
      @ok="handleConfirmEdit"
      @cancel="handleCancelEdit"
      :confirm-loading="editLoading"
    >
      <a-form ref="editFormRef" :model="editForm" :rules="editRules" layout="vertical">
        <a-form-item label="空间名称" name="spaceName">
          <a-input v-model:value="editForm.spaceName" placeholder="请输入空间名称" />
        </a-form-item>
        <a-form-item label="空间级别" name="spaceLevel">
          <a-select v-model:value="editForm.spaceLevel" placeholder="请选择空间级别">
            <a-select-option
              v-for="option in SPACE_LEVEL_OPTIONS"
              :key="option.value"
              :value="option.value"
            >
              {{ option.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="空间类型" name="spaceType">
          <a-select v-model:value="editForm.spaceType" placeholder="请选择空间类型">
            <a-select-option
              v-for="option in SPACE_TYPE_OPTIONS"
              :key="option.value"
              :value="option.value"
            >
              {{ option.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import {
  SearchOutlined,
  ReloadOutlined,
  EyeOutlined,
  EditOutlined,
  DeleteOutlined,
  DatabaseOutlined,
  UserOutlined,
  TeamOutlined,
  PlusOutlined,
} from '@ant-design/icons-vue'
import { listSpaceByPage, getSpaceById, updateSpace, deleteSpace } from '@/api/space'
import type { Space, SpaceQueryRequest, SpaceUpdateRequest } from '@/types/space'
import {
  SPACE_LEVEL_OPTIONS,
  SPACE_TYPE_OPTIONS,
  getSpaceLevelText,
  getSpaceLevelColor,
  getSpaceTypeText,
  getSpaceTypeColor,
} from '@/types/space'
import type { FormInstance } from 'ant-design-vue'

// 响应式数据
const loading = ref(false)
const editLoading = ref(false)
const spaceList = ref<Space[]>([])
const detailModalVisible = ref(false)
const editModalVisible = ref(false)
const currentSpace = ref<Space | null>(null)
const editFormRef = ref<FormInstance>()

// 搜索表单
const searchForm = reactive<SpaceQueryRequest>({
  spaceName: '',
  spaceLevel: undefined,
  spaceType: undefined,
  current: 1,
  pageSize: 10,
})

// 编辑表单
const editForm = reactive<SpaceUpdateRequest>({
  id: '0',
  spaceName: '',
  spaceLevel: 0,
  spaceType: 0,
})

// 编辑表单验证规则
const editRules = {
  spaceName: [
    { required: true, message: '请输入空间名称' },
    { max: 50, message: '空间名称不能超过50个字符' },
  ],
  spaceLevel: [{ required: true, message: '请选择空间级别' }],
  spaceType: [{ required: true, message: '请选择空间类型' }],
}

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
})

// 表格列配置
const columns = [
  {
    title: '空间名称',
    key: 'spaceName',
    dataIndex: 'spaceName',
    width: 200,
  },
  {
    title: '空间级别',
    key: 'spaceLevel',
    dataIndex: 'spaceLevel',
    width: 120,
  },
  {
    title: '空间类型',
    key: 'spaceType',
    dataIndex: 'spaceType',
    width: 120,
  },
  {
    title: '创建用户ID',
    dataIndex: 'userId',
    key: 'userId',
    width: 120,
  },
  {
    title: '创建时间',
    key: 'createTime',
    dataIndex: 'createTime',
    width: 180,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right' as const,
  },
]

// 统计信息
const stats = computed(() => {
  const personal = spaceList.value.filter((space) => space.spaceType === 0).length
  const team = spaceList.value.filter((space) => space.spaceType === 1).length
  const todayNew = spaceList.value.filter((space) => {
    return dayjs(space.createTime).isSame(dayjs(), 'day')
  }).length

  return {
    total: spaceList.value.length,
    personal,
    team,
    todayNew,
  }
})

// 获取空间列表
const fetchSpaceList = async () => {
  try {
    loading.value = true
    const params = {
      ...searchForm,
      current: pagination.current,
      pageSize: pagination.pageSize,
    }
    const response = await listSpaceByPage(params)
    spaceList.value = response.data.data.records
    pagination.total = response.data.data.total
  } catch (error) {
    console.error('获取空间列表失败:', error)
    // 如果后端空间接口尚未实现，不显示错误提示
    spaceList.value = []
    pagination.total = 0
    // message.error('空间管理功能暂未开放，敬请期待')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchSpaceList()
}

// 重置
const handleReset = () => {
  searchForm.spaceName = ''
  searchForm.spaceLevel = undefined
  searchForm.spaceType = undefined
  pagination.current = 1
  fetchSpaceList()
}

// 表格变化处理
const handleTableChange = (pag: { current: number; pageSize: number }) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  fetchSpaceList()
}

// 查看空间详情
const handleView = async (space: Space) => {
  try {
    const response = await getSpaceById(space.id)
    currentSpace.value = response.data.data
    detailModalVisible.value = true
  } catch (error) {
    console.error('获取空间详情失败:', error)
    message.error('获取空间详情失败')
  }
}

// 编辑空间
const handleEdit = (space: Space) => {
  editForm.id = space.id
  editForm.spaceName = space.spaceName
  editForm.spaceLevel = space.spaceLevel
  editForm.spaceType = space.spaceType
  editModalVisible.value = true
}

// 确认编辑
const handleConfirmEdit = () => {
  editFormRef.value
    ?.validateFields()
    .then(async () => {
      try {
        editLoading.value = true
        await updateSpace(editForm)
        message.success('编辑空间成功')
        editModalVisible.value = false
        fetchSpaceList()
      } catch (error) {
        console.error('编辑空间失败:', error)
        message.error('编辑空间失败')
      } finally {
        editLoading.value = false
      }
    })
    .catch(() => {
      // 验证失败，不做任何处理
    })
}

// 取消编辑
const handleCancelEdit = () => {
  editModalVisible.value = false
  editFormRef.value?.resetFields()
}

// 删除空间
const handleDelete = async (space: Space) => {
  try {
    await deleteSpace({ id: space.id })
    message.success('删除空间成功')
    fetchSpaceList()
  } catch (error) {
    console.error('删除空间失败:', error)
    message.error('删除空间失败')
  }
}

// 格式化日期
const formatDate = (dateString?: string) => {
  if (!dateString) return '-'
  return dayjs(dateString).format('YYYY-MM-DD HH:mm:ss')
}

// 组件挂载时获取数据
onMounted(() => {
  fetchSpaceList()
})
</script>

<style scoped>
.space-manage-container {
  padding: 24px;
}

.search-form {
  margin-bottom: 16px;
  padding: 24px;
  background: #fafafa;
  border-radius: 8px;
}

.stats-cards {
  margin-bottom: 24px;
}

.space-list {
  background: white;
  border-radius: 8px;
}

.space-name-cell {
  display: flex;
  flex-direction: column;
}

.space-id {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.space-detail {
  padding: 16px;
}

:deep(.ant-table-thead > tr > th) {
  background-color: #fafafa;
  font-weight: 600;
}

:deep(.ant-descriptions-title) {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 16px;
}

:deep(.ant-statistic-title) {
  font-size: 14px;
  color: #666;
}

:deep(.ant-statistic-content) {
  font-size: 24px;
  font-weight: 600;
}
</style>
